<template>
  <div class="designer-container">
    <div  ref="canvas" style="flex: 1; border: 1px solid #e4e7ed;"></div>
    <div style="display: flex; height: 600px;">
      <div  ref="canvas" style="flex: 1; border: 1px solid #e4e7ed;"></div>
      <div ref="propertiesPanel" style="width: 300px; border-left: 1px solid #e4e7ed;"></div>
    </div>
    <div class="button-group">
      <el-button type="primary" @click="saveProcess">保存流程</el-button>
      <el-button type="success" @click="resetCanvas">重置流程</el-button>
    </div>
  </div>
</template>

<script>

import BpmnModeler from 'bpmn-js/lib/Modeler';
import { Message } from 'element-ui';
import request from '@/utils/request';
import propertiesPanelModule from 'bpmn-js-properties-panel';
import camundaPropertiesProvider from 'bpmn-js-properties-panel/lib/provider/camunda';
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda.json'; // 关键元数据导入

// 样式导入（确保路径正确）
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import { listDefinition, getDefinition, delDefinition, addDefinition, updateDefinition } from "@/api/engine/definition";

export default {
  data() {
    return {
      processkey:"",
      bpmnModeler: null,
      initialXml: `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://www.activiti.org/processdef">
  <process id="leaveProcess" name="标准项目审核流程" isExecutable="true">
    <startEvent id="start" name="开始" />
    <userTask id="applyTask" name="请假申请" camunda:assignee="group" />
    <endEvent id="end" name="结束">
      <incoming>Flow_0d2swow</incoming>
    </endEvent>
    <sequenceFlow id="flow1" sourceRef="start" targetRef="applyTask" />
    <sequenceFlow id="flow2" sourceRef="applyTask" targetRef="Activity_1rl7rsw" />
    <sequenceFlow id="Flow_10lcos9" sourceRef="Activity_1en0wz0" targetRef="Activity_0b7zdka" />
    <sequenceFlow id="Flow_0d2swow" sourceRef="Activity_0b7zdka" targetRef="end" />
    <serviceTask id="Activity_0b7zdka" name="结束" camunda:class="com.ruoyi.listener.LeaveRequestService">
      <incoming>Flow_10lcos9</incoming>
      <outgoing>Flow_0d2swow</outgoing>
    </serviceTask>
    <userTask id="Activity_1rl7rsw" name="团长" camunda:assignee="regimental">
      <incoming>flow2</incoming>
      <outgoing>Flow_172dtxu</outgoing>
    </userTask>
    <userTask id="Activity_1en0wz0" name="负责人" camunda:assignee="charge">
      <incoming>Flow_172dtxu</incoming>
      <outgoing>Flow_10lcos9</outgoing>
    </userTask>
    <sequenceFlow id="Flow_172dtxu" sourceRef="Activity_1rl7rsw" targetRef="Activity_1en0wz0" />
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_1">
    <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="leaveProcess">
      <bpmndi:BPMNEdge id="Flow_0d2swow_di" bpmnElement="Flow_0d2swow">
        <omgdi:waypoint x="688" y="270" />
        <omgdi:waypoint x="688" y="299" />
        <omgdi:waypoint x="745" y="299" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge id="Flow_10lcos9_di" bpmnElement="Flow_10lcos9">
        <omgdi:waypoint x="630" y="114" />
        <omgdi:waypoint x="688" y="114" />
        <omgdi:waypoint x="688" y="190" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge id="flow2_di" bpmnElement="flow2">
        <omgdi:waypoint x="300" y="125" />
        <omgdi:waypoint x="365" y="125" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge id="flow1_di" bpmnElement="flow1">
        <omgdi:waypoint x="130" y="115" />
        <omgdi:waypoint x="200" y="120" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge id="Flow_172dtxu_di" bpmnElement="Flow_172dtxu">
        <omgdi:waypoint x="465" y="114" />
        <omgdi:waypoint x="530" y="114" />
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNShape id="start_di" bpmnElement="start">
        <omgdc:Bounds x="100" y="100" width="30" height="30" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="applyTask_di" bpmnElement="applyTask">
        <omgdc:Bounds x="200" y="80" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="end_di" bpmnElement="end">
        <omgdc:Bounds x="745" y="285" width="30" height="30" />
        <bpmndi:BPMNLabel>
          <omgdc:Bounds x="749" y="315" width="22" height="14" />
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="Activity_16w9f12_di" bpmnElement="Activity_0b7zdka">
        <omgdc:Bounds x="638" y="190" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="Activity_15oa8qq_di" bpmnElement="Activity_1en0wz0">
        <omgdc:Bounds x="530" y="74" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="Activity_10vow5t_di" bpmnElement="Activity_1rl7rsw">
        <omgdc:Bounds x="365" y="85" width="100" height="80" />
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>`
    };
  },

  mounted() {
    this.initModeler();
  },

  methods: {
    /** 查询模版引擎管理列表 */
    getList() {
      this.loading = true;
      listDefinition(this.queryParams).then(response => {
        this.definitionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    async initModeler() {
       await listDefinition(this.queryParams).then(response => {
        this.definitionList = response.rows;
        this.initialXml=response.rows[0].bpmnXml;
        console.log(this.initialXml);
      });
      this.bpmnModeler = new BpmnModeler({
        container: this.$refs.canvas,
        // 注册Camunda元数据（解决unknown type错误）
        moddleExtensions: {
          camunda: camundaModdleDescriptor
        },
        additionalModules: [
          propertiesPanelModule,
          camundaPropertiesProvider // 启用Camunda属性面板
        ],
        propertiesPanel: {
          parent: this.$refs.propertiesPanel // 绑定属性面板容器
        },
        palette: {
          entries: (entries) => entries.filter(entry => !entry.action?.startsWith('create.group'))
        }
      });

      this.loadInitialProcess();
    },

    loadInitialProcess() {
      this.bpmnModeler.importXML(this.initialXml)
        .then(() => {
          Message.success('初始流程加载成功！');
          this.bpmnModeler.get('canvas').zoom('fit-viewport');
        })
        .catch(err => {
          console.error('加载失败:', err);
          Message.error('初始流程加载失败，请检查 XML 格式');
        });
    },
 // 提取流程定义 ID 和名称
  extractProcessInfo(xmlString) {
    try {
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xmlString, 'text/xml');

      // 获取 <process> 元素
      const processElement = xmlDoc.querySelector('process');
      if (!processElement) {
        console.error('未找到 process 元素');
        return null;
      }

      // 提取 ID 和名称
      const processId = processElement.getAttribute('id');
      const processName = processElement.getAttribute('name');
      this.processKey = processId
      console.log(this.processKey)
      // 尝试提取版本信息（如果使用 camunda:versionTag 扩展属性）
      const versionElement = processElement.querySelector('[camunda\\:versionTag]');
      const version = versionElement
        ? versionElement.getAttribute('camunda:versionTag')
        : null;

      return {
        id: processId,
        name: processName,
        version: version || '未指定版本'
      };
    } catch (error) {
      console.error('解析 BPMN XML 失败:', error);
      return null;
    }
  },

    async saveProcess() {

      const { xml } = await this.bpmnModeler.saveXML({ format: true });

      // 提取流程信息
      const processInfo = this.extractProcessInfo(xml);

// addDefinition({processKey:processInfo.id,bpmnXml:xml,}).then(response => {
//               this.$modal.msgSuccess("新增成功");
//             });
updateDefinition({bpmnXml:xml,processKey:processInfo.id}).then(response => {
  if(response.code == 200){
 this.$modal.msgSuccess("更新成功");
  }else{
    this.$modal.error("更新失败");
  }

            });

    },

    async resetCanvas() {
//         const { xml } = await this.bpmnModeler.saveXML({ format: true });
//  console.log(xml)
//  return
      this.bpmnModeler.importXML(this.initialXml);
      Message.success('流程已重置');
    }
  },

  beforeDestroy() {
    this.bpmnModeler?.destroy();
  }
};
</script>

<style scoped>
.designer-container {
  padding: 20px;
  background: #fff;
}
</style>
